<?php

/*
* File Name: RedisModule.php
* Author: Len
* mail: i@91coder.org
* Created Time: Mon 27 Mar 2017 01:14:43 AM CST
*/

class RedisModule
{

    static $redis;

    private function __construct()
    {
    }

    public static function connect($config)
    {
        if (!empty(self::$redis) && self::$redis->isConnected()) {

            return self::$redis;
        }

        try {
            $redis = new redis();
            $redis->pconnect($config['host'], $config['port']);
            !empty($config['pwd']) && $redis->auth($config['pwd']);
        } catch (Exception $e) {
            Log::error('connect: ' . $e->getMessage());

            return false;
        }

        return self::$redis = $redis;
    }

    public static function reload($config)
    {
        self::$redis = null;

        return self::connect($config);
    }

    public static function lpop($key)
    {
        if (empty(self::$redis)) return false;
        try {
            $msgData = self::$redis->lpop($key);
        } catch (\Exception $e) {
            Log::error('lpop: ' . $e->getMessage());
            return false;
        }

        return $msgData;
    }

    public static function rpush($key, $msgData)
    {
        if (empty(self::$redis)) return false;
        try {
            $curLen = self::$redis->rpush($key, $msgData);
        } catch (\Exception $e) {
            Log::error('rpush: ' . $e->getMessage());
            return false;
        }

        return $curLen;
    }

    public static function info()
    {
        if (empty(self::$redis)) return false;
        try {
            $info = self::$redis->info('Clients');
        } catch (\Exception $e) {
            Log::error('info(clients): ' . $e->getMessage());
            return false;
        }

        return !empty($info['connected_clients']);
    }
}
